<?php

class Skjb_Office_Spreadsheet_Exporter_Excel2007Xml_SharedStrings
{
    protected $_spreadsheet = null;
    
    protected $_uniqueStrings = array();
    
    public function __construct($spreadsheet)
    {
        $this->_spreadsheet = $spreadsheet;
    }
    
    public function toXml()
    {
        $strings = array();
        
        foreach ($this->_spreadsheet->sheets as $sheet) {
            foreach ($sheet->rows as $row) {
                foreach ($row->cells as $cell) {
                    $value = $cell->getDisplayValue();
                    if (!is_numeric($value)) {
                        $strings[] = $value;
                    }
                }
            }
        }
        
        $this->_uniqueStrings = array_unique($strings);
        
        $xml = new XMLWriter();
        $xml->openMemory();
        
        $xml->startDocument('1.0', 'UTF-8', 'yes');
            $xml->startElement('sst');
                $xml->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
                $xml->writeAttribute('count', count($strings));
                $xml->writeAttribute('uniqueCount', count($this->_uniqueStrings));
                
                foreach ($this->_uniqueStrings as $string) {
                    $xml->startElement('si');
                        $xml->startElement('t');
                            $xml->writeRaw($string);
                        $xml->endElement(); // t
                    $xml->endElement(); // si
                }
                
            $xml->endElement(); // sst
        $xml->endDocument();
        
        return $xml->outputMemory();
    }
    
    public function getStringIndex($string)
    {
        return array_search($string, $this->_uniqueStrings);
    }
}
